import re

from datetime import datetime

from electricity_supplier_project import instance_list
from operator_log.models import OperatorLog


class DataReCordMiddleware(object):
    def __init__(self, get_response):
        # 中间件初始化
        self.get_response = get_response
        self.action_time = None  # 操作时间

    def __call__(self, request):
        api = request.path_info  # 2-获得请求的API
        matchApi = re.match('/operator/', api)
        request_method = request.method  # 3-获得请求的方法
        response = self.get_response(request)
        message = ''
        if matchApi and request_method == 'POST' and instance_list:
            message = '创建了' + str(instance_list[0])
        if matchApi and request_method == 'PUT' and instance_list:
            message = '修改了' + str(instance_list[0])
        if matchApi and request_method == 'DELETE' and instance_list:
            message = '删除了' + str(instance_list[0])
        if request.user.is_authenticated and message:
            user = request.user  # 1-获取用户
            create_record(user, message)
        return response


def create_record(user, message):
    """
    创建记录
    :param user: 操作管理员
    :param message: 操作记录
    :return:
    """
    record_count = 1000
    if OperatorLog.objects.count() > record_count:
        OperatorLog.objects.order_by('action_time').first().delete()
    OperatorLog.objects.create(user=user, message=message, action_time=datetime.now())
